import 'dart:async';
import 'dart:core';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';

import '../ssh_service.dart';
import 'console_controller.dart';

class CustomCmdController extends ConsoleController {
  final _selectIpList = <String>[];
  final allSelectListLength = 0.obs;
  final selectIpController = ScrollController();
  late final StreamSubscription<SshCfgEvent> evt;

  CustomCmdController({List<String>? selIpList}) : super() {
    if (selIpList != null) {
      _selectIpList.assignAll(selIpList);
      allSelectListLength.value = _selectIpList.length;
    }
  }

  @override
  void onInit() {
    super.onInit();
    SshService srv = Get.find();
    evt = srv.eventBus.on<SshCfgEvent>().listen((event) {
      if (event.event == SshCfgEvent.eventIP) {
        _selectIpList.removeWhere(
            (selIP) => !srv.allIpList.any((validIP) => selIP == validIP));
        allSelectListLength.value = _selectIpList.length;
        allSelectListLength.refresh();
      }
    });
  }

  @override
  void onClose() {
    evt.cancel();
    super.onClose();
  }

  Iterable<String> get allSelectList {
    return _selectIpList.followedBy([]);
  }

  Iterable<String> get allIpListNotInCluster {
    return Get.find<SshService>().allIpListNotInCluster;
  }

  List<String>? getIpListByCluster(String cluster) {
    return Get.find<SshService>().clusters[cluster];
  }

  Iterable<String> get allClusterList {
    return Get.find<SshService>().allClusterList;
  }

  void assignSelectIp(List<String> ipList) {
    _selectIpList.assignAll(ipList.toSet().toList());
    allSelectListLength.value = _selectIpList.length;
    allSelectListLength.refresh();
  }

  void deleteFromSelectIp(Iterable<String> ipList) {
    _selectIpList.removeWhere((selIP) => ipList.any((rmIP) => selIP == rmIP));
    allSelectListLength.value = _selectIpList.length;
    allSelectListLength.refresh();
  }

  List<List<String>> getMatchCmd(String val) {
    List<List<String>> ret = [];
    customCmd.forEach((key, value) {
      if (key.contains(val)) {
        ret.add([key, value]);
      }
    });
    return ret;
  }
}
